<template>
	<view class="wrapper">
		<view class="content-wrap">
			<!-- <scroll-view> -->
			<uni-forms
				:modelValue="formData"
				:rules="rules"
				ref="form"
				label-width="150"
				label-position="top"
			>
				<uni-forms-item label="方案名" required name="planName">
					<uni-easyinput
						type="text"
						v-model="formData.planName"
						placeholder="请输入方案名"
					/>
				</uni-forms-item>
				<uni-card title="客户信息" :isFull="true">
					<uni-forms-item label="客户姓名" required name="customName">
						<uni-easyinput
							type="text"
							v-model="formData.customName"
							placeholder="请输入客户姓名"
						/>
					</uni-forms-item>
					<uni-forms-item label="客户地址" required name="customAddress">
						<uni-easyinput
							type="text"
							v-model="formData.customAddress"
							placeholder="请输入客户地址"
						/>
					</uni-forms-item>
					<uni-forms-item label="客户电话" required name="customPhone">
						<uni-easyinput
							type="text"
							v-model="formData.customPhone"
							placeholder="请输入客户电话"
						/>
					</uni-forms-item>
				</uni-card>
				<view
					class="space-wrapper"
					v-for="(item, index) in formData.list"
					:key="index"
				>
					<uni-card :title="'空间信息' + (index + 1)" :isFull="true">
						<uni-forms-item label="空间" required>
							<uni-data-select
								v-model="item.name"
								:localdata="spaceList"
							></uni-data-select>
						</uni-forms-item>
						<view
							class="space-wrapper"
							v-for="(category, i) in item.list"
							:key="i"
						>
							<uni-card :title="'产品' + (i + 1)" :isFull="true">
								<uni-forms-item label="产品类别" required>
									<uni-data-select
										v-model="category.category"
										:localdata="categoryList"
									></uni-data-select>
								</uni-forms-item>
								<uni-forms-item label="单价" required>
									<uni-data-select
										disabled
										v-model="category.category"
										:localdata="categoryPriceList"
									></uni-data-select>
								</uni-forms-item>
								<uni-forms-item label="数量" required>
									<uni-data-select
										v-model="category.number"
										:localdata="numberList"
									></uni-data-select>
								</uni-forms-item>
								<uni-forms-item label="总价" required>
									<uni-easyinput
										disabled
										:value="
											category.number && category.category
												? parseInt((category.number || 0) + '') *
												  parseFloat(
														categoryPriceList.find(
															(f) => f.value === category.category
														)?.text || '0'
												  )
												: 0
										"
									/>
								</uni-forms-item>
								<!-- <uni-forms-item label="产品二级类别" required>
									<uni-data-select
										v-model="category.secondCategory"
										:localdata="secondCategoryList"
									></uni-data-select>
								</uni-forms-item> -->
								<uni-forms-item label="特性" required>
									<view class="uni-list-cell-db">
										<view class="as-input" @click="() => openFeature(index, i)">
											<view
												class="placeholder"
												v-if="
													category.feature == undefined ||
													category.feature == ''
												"
												>请选择特性</view
											>
											<view class="as-content" v-else>{{
												getFeatureName(category.feature)
											}}</view>
											<uni-icons
												type="forward"
												size="16"
												color="#c0c4cc"
												class="customer-icon"
											></uni-icons>
										</view>
									</view>
								</uni-forms-item>
								<uni-forms-item label="实物图">
									<image
										:src="getImg(category.category)"
										model="aspectFit"
										class="image-category"
									/>
								</uni-forms-item>
							</uni-card>
							<button
								class="danger"
								type="danger"
								v-if="item.list.length > 1"
								@click="() => deleteDevice(index, i)"
							>
								删除设备
							</button>
						</view>
						<button
							class="button"
							type="primary"
							@click="() => addCategory(index)"
						>
							添加设备
						</button>
						<button
							class="danger"
							type="danger"
							v-if="formData.list.length > 1"
							@click="() => deleteSpace(index)"
						>
							删除空间
						</button>
					</uni-card>
				</view>
				<button class="button" type="primary" @click="addSpace">
					添加空间
				</button>
				<uni-forms-item label="安装调试费类型">
						<uni-data-checkbox v-model="formData.installType" :localdata="installs" />
				</uni-forms-item>
				<uni-forms-item label="安装调试费" v-show="formData.installType===0">
					<uni-easyinput
						type="number"
						v-model="formData.installPrice"
						placeholder="安装调试费"
					/>
				</uni-forms-item>
				<uni-forms-item label="安装调试费百分比" v-show="formData.installType===1">
					<uni-easyinput
						type="number"
						v-model="formData.installPricePercent"
						placeholder="安装调试费百分比"
					/>
				</uni-forms-item>
		
				<uni-forms-item label="优惠金额">
					<uni-easyinput
						type="number"
						v-model="formData.discount"
						placeholder="请输入优惠金额"
					/>
				</uni-forms-item>
				<uni-forms-item label="其他成本">
					<uni-easyinput
						type="number"
						v-model="formData.other"
						placeholder="请输入其他成本"
					/>
				</uni-forms-item>
			</uni-forms>
	
	<view class="amount-container">
	  <view class="amount-item">
	    <text class="label">产品费用：</text>
	    <text class="value">¥{{ getProductPrice().toFixed(2) }}</text>
	  </view>
	  <view class="divider"></view>
	  <view class="amount-item">
	    <text class="label">产品成本：</text>
	    <text class="value">¥{{ getProductpurchasPrice().toFixed(2) }}</text>
	  </view>
	  <view class="divider"></view>
	  <view class="amount-item">
	    <text class="label">利润：</text>
	    <text class="value profit-value">¥{{ getProfit().toFixed(2) }}</text>
	  </view>
	</view>
			
		</view>
		<view class="bottom">
			<view class="fill"
				>合计<text>¥ {{ getPrice() }}</text></view
			>
			<view class="flex">
				<view class="fill" @click="downloadMaterial">
					<uni-icons type="cart" size="18"></uni-icons>
				</view>
				<view class="fill" @click="go2Temp">
					<uni-icons type="compose" size="18"></uni-icons>
				</view>
			</view>
		</view>
		<popup-select
			ref="showPopSelect"
			:columns="featureList"
			:selectValue="featureId"
			:multiple="true"
			 :key="selectKey"
			:option="{ label: 'name', value: 'id' }"
			@confirm="confirmFeature"
		></popup-select>
		<uni-popup ref="inputDialog" type="dialog">
			<view class="form-container">
				<uni-forms
					:modelValue="formData"
					:rules="rules"
					ref="form"
					label-position="top"
				>
					<uni-forms-item label="定金" required name="preMoney">
						<uni-easyinput
							type="number"
							v-model="formData.preMoney"
							placeholder="请输入定金"
						/>
					</uni-forms-item>
				</uni-forms>
				<button class="button" type="primary" @click="submit">生成合同</button>
			</view>
		</uni-popup>
	</view>
</template>
<script>
import PopupSelect from '../../components/popup-select/popup-select.vue'
export default {
	components: {
		PopupSelect
	},
	data() {
		return {
			formData: {
				planName: '',
				customName: '',
				customPhone: '',
				customAddress: '',
				discount: 0,
				preMoney: 0,
				list: [
					{
						name: '',
						list: [],
						total: 0,
						id: new Date().getTime().toString()
					}
				],
				installType:0,
				installPrice:0,
				installPricePercent:0,
				other:0,
		        confirmDate:''
			},
			numberList: [
				{
					text: '1',
					value: '1'
				},
				{ text: '2', value: '2' },
				{ text: '3', value: '3' },
				{ text: '4', value: '4' },
				{ text: '5', value: '5' },
				{ text: '6', value: '6' },
				{ text: '7', value: '7' },
				{ text: '8', value: '8' },
				{ text: '9', value: '9' },
				{ text: '10', value: '10' },
				{ text: '11', value: '11' },
				{ text: '12', value: '12' },
				{ text: '13', value: '13' },
				{ text: '14', value: '14' },
				{ text: '15', value: '15' },
				{ text: '16', value: '16' },
				{ text: '17', value: '17' },
				{ text: '18', value: '18' },
				{ text: '19', value: '19' },
				{ text: '20', value: '20' }
			],
			featureId: [],
			spaceList: [],
			categoryList: [],
			categoryPriceList: [],
			secondCategoryList: [],
			featureList: [],
			firstIndex: 0,
			secondIndex: 0,
			rules: {
				planName: {
					rules: [
						{
							required: true,
							errorMessage: '请输入方案名'
						}
					]
				},
				customName: {
					rules: [
						{
							required: true,
							errorMessage: '请输入客户姓名'
						}
					]
				},
				customPhone: {
					rules: [
						{
							required: true,
							errorMessage: '请输入客户电话'
						}
					]
				},
				preMoney: {
					rules: [
						{
							required: true,
							errorMessage: '请输入定金'
						}
					]
				},
				customAddress: {
					rules: [
						{
							required: true,
							errorMessage: '请输入客户地址'
						}
					]
				}
			},installs: [{
					text: '金额',
					value: 0
				}, {
					text: '百分比',
					value: 1
				}],
				selectKey:0
		}
	},

	methods: {
		addSpace() {
			this.formData.list.push({
				name: '',
				list: [],
				total: 0,
				id: new Date().getTime().toString()
			})
		},
		submit() {
			uni.showLoading()
			var that = this;
			this.$refs.form
				.validate()
				.then((res) => {
					const confirmDate =that.getCurrentDate();
					this.formData.confirmDate = confirmDate;
					uni.hideLoading()
					console.log('表单数据信息：', res, this.formData)
					uni.navigateTo({
						url:
							'/pages/my/doc?data=' +
							encodeURIComponent(JSON.stringify(this.formData))
					})
				})
				.catch((err) => {
					uni.hideLoading()
					console.log('表单错误信息：', err)
				})
		},
		getCurrentDate() {
		  const now = new Date();
	      const year = String(now.getFullYear()).slice(-2); // 获取最后两位数字
		  const month = String(now.getMonth() + 1).padStart(2, '0');
		  const day = String(now.getDate()).padStart(2, '0');
		  
		  return `${year}/${month}/${day}`;
		},
		
		confirmFeature(data) {
			console.log(data)
			this.formData.list[this.firstIndex].list[this.secondIndex].feature = data
			this.$refs.showPopSelect.cancel();
			 
		},

		getImg(categoryId) {
			return this.categoryList.find((f) => f.value === categoryId).image
		},
		getData() {
			const content = uni.getStorageSync('space_list_key')
			if (content) {
				this.spaceList = JSON.parse(content).map((m) => {
					return {
						value: m.id,
						text: m.name
					}
				})
			}
			const secondCategoryList = uni.getStorageSync('second_category_list_key')
			if (secondCategoryList) {
				this.secondCategoryList = JSON.parse(secondCategoryList).map((m) => {
					return {
						value: m.id,
						text: m.name
					}
				})
			}
			const feature = uni.getStorageSync('feature_list_key')
			if (feature) {
				this.featureList = JSON.parse(feature).map((m) => {
					return {
						id: m.id,
						name: m.name
					}
				})
			}
			const category = uni.getStorageSync('category_list_key')
			if (category) {
				this.categoryList = JSON.parse(category).map((m) => {
					return {
						value: m.id,
						text: m.name,
						image: m.image
					}
				})
				this.categoryPriceList = JSON.parse(category).map((m) => {
				
					return {
						value: m.id,
						text: m.price,
						purchasePrice:m.purchasePrice||0
					}
				})
			}
			
		},
		addCategory(index) {
			this.formData.list[index].list.push({
				category: '',
				total: 0,
				id: new Date().getTime().toString()
			})
		},
		openFeature(index, i) {
			this.featureId = this.formData.list[index].list[i].feature || []
			this.selectKey += 1;
			this.firstIndex = index
			this.secondIndex = i
			setTimeout(() => {
				this.$refs.showPopSelect.showPopup()
			}, 300)
			
			// this.$refs.showPopSelect.showPopup()
		},
		deleteSpace(index) {
			this.formData.list.splice(index, 1)
		},
		deleteDevice(index, i) {
			this.formData.list[index].list.splice(i, 1)
		},
		getFeatureName(ids) {
			if (ids) {
				const arr = []
				ids.forEach((f) => {
					arr.push(this.featureList.find((d) => d.id === f).name)
				})
				return arr.join('/')
			}
		},
		
		getProfit(){
			var total = this.getPrice();
			var pr = this.getProductPrice();
			var ot = this.formData.other;
			return this.getPrice()-this.getProductpurchasPrice()-(this.formData.other||0);
		},
		getProductPrice() {
			let total = 0
			
			let purchasePrice = 0;
			this.formData.list.forEach((f) => {
				f.list.forEach((d) => {
					if (d.number && d.category) {
						total +=
							parseInt((d.number || 0) + '') *
							parseFloat(
								this.categoryPriceList.find((f) => f.value === d.category)
									?.text || '0'
							)
					}
				})
				
			})
			
			return total
		},
		
		getProductpurchasPrice() {
			let total = 0
			this.formData.list.forEach((f) => {
				f.list.forEach((d) => {
					if (d.number && d.category ) {
						console.log(d.category)
						var da = this.categoryPriceList.find((f) => f.value === d.category);
						console.log(JSON.stringify(da))
						total +=
							parseInt((d.number || 0) + '') *
							parseFloat(
								this.categoryPriceList.find((f) => f.value === d.category)
									?.purchasePrice || '0'
							)
					}
				})
			})
			
			return total
		},
		
		getPrice() {
			let total = 0
			this.formData.list.forEach((f) => {
				f.list.forEach((d) => {
					if (d.number && d.category) {
						total +=
							parseInt((d.number || 0) + '') *
							parseFloat(
								this.categoryPriceList.find((f) => f.value === d.category)
									?.text || '0'
							)
					}
				})
			})
		
			let installationFee = 0;
			if (this.formData.installType === 1) { // Percentage
			    const productTotal = this.getProductPrice();
				
			   installationFee = productTotal * (parseFloat(this.formData.installPricePercent || 0) / 100);
			} else { // Fixed amount
			    installationFee = parseFloat(this.formData.installPrice || 0);
			}
			this.formData.installPrice = installationFee;
			 // Add installation fee to total
			 total += installationFee; 
			  // Apply discount if any
			  if (this.formData.discount) {
			    total -= parseFloat((this.formData.discount || 0) + '')
			  }
			  return total
		},
		downloadMaterial() {
			uni.navigateTo({
				url:
					'/pages/my/material?data=' +
					encodeURIComponent(JSON.stringify(this.formData))
			})
		},
		go2Temp() {
			// uni.navigateTo({
			// 	url:
			// 		'/pages/my/doc?data=' +
			// 		encodeURIComponent(JSON.stringify(this.formData))
			// })
			this.$refs.inputDialog.open()
		}
	},
	onLoad(e) {
		if (e.id) {
			const content = uni.getStorageSync('plan_list_key')
			if (content) {
				const arr = JSON.parse(content)
				this.formData = arr.find((f) => f.id === e.id)
			}
		}
		this.getData()
	},

	onNavigationBarButtonTap: function (e) {
		console.log(e)
		// e的返回格式为json对象：{"text":"测试","index":0}
		switch (e.index) {
			case 0:
				uni.showLoading()
				this.$refs.form
					.validate()
					.then((res) => {
						uni.hideLoading()
						const plan_list_key = uni.getStorageSync('plan_list_key')
						if (plan_list_key) {
							const arr = JSON.parse(plan_list_key)
							if (this.formData.id) {
								arr.splice(
									arr.findIndex((f) => f.id === this.formData.id),
									1,
									this.formData
								)
							} else {
								this.formData.id = new Date().getTime().toString()
								arr.push(this.formData)
							}
							uni.setStorageSync('plan_list_key', JSON.stringify(arr))
						} else {
							uni.setStorageSync(
								'plan_list_key',
								JSON.stringify([
									{
										...this.formData,
										id: new Date().getTime().toString()
									}
								])
							)
						}
						uni.navigateBack()
						uni.showToast({
							title: '保存成功',
							icon: 'success',
							duration: 2000
						})
						console.log('表单数据信息：', this.formData)
					})
					.catch((err) => {
						uni.hideLoading()
						console.log('表单错误信息：', err)
					})

				break
			case 1:
				uni.navigateTo({
					url:
						'/pages/my/preview?data=' +
						encodeURIComponent(JSON.stringify(this.formData))
				})
				// let csvRows = [
				// 	['', '', '', '全屋智能设备清单空间汇总方案'],
				// 	[('客户姓名', this.formData.customName)],
				// 	['客户地址', this.formData.customAddress],
				// 	[
				// 		'客户电话',
				// 		`"${this.formData.customPhone.toLocaleString('fullwide', {
				// 			useGrouping: false
				// 		})}"`
				// 	],
				// 	[]
				// 	// ...this.formData.list.map((f) => {
				// 	// 	return ['空间', this.spaceList.find((d) => d.value === f.name).text]
				// 	// })
				// 	// ['空间', '产品类别', '产品二级类别', '单价', '数量', '总价', '特性']
				// 	// ... add your data rows here ...
				// ]
				// let allTotal = 0
				// this.formData.list.forEach((f) => {
				// 	csvRows.push([
				// 		'空间',
				// 		this.spaceList.find((d) => d.value === f.name).text
				// 	])
				// 	// f.list.forEach((d) => {
				// 	let temp = []
				// 	temp.push([
				// 		'产品类别'
				// 		// this.categoryList.find((f) => f.value === d.category).text
				// 	])
				// 	// temp.push([
				// 	// 	'产品二级类别'
				// 	// 	// this.secondCategoryList.find((f) => f.value === d.secondCategory)
				// 	// 	// 	.text
				// 	// ])
				// 	temp.push([
				// 		'单价'
				// 		// this.categoryPriceList.find((f) => f.value === d.category).text
				// 	])
				// 	temp.push(['数量'])
				// 	temp.push(['总价'])
				// 	temp.push(['特性'])
				// 	temp.push(['实物图'])
				// 	csvRows.push(temp)
				// 	// })
				// 	let total = 0
				// 	f.list.forEach((d) => {
				// 		let temp = []
				// 		total +=
				// 			d.number *
				// 			parseFloat(
				// 				this.categoryPriceList.find((f) => f.value === d.category).text
				// 			)
				// 		temp.push([
				// 			this.categoryList.find((f) => f.value === d.category).text
				// 		])
				// 		// temp.push([
				// 		// 	this.secondCategoryList.find((f) => f.value === d.secondCategory)
				// 		// 		.text
				// 		// ])
				// 		temp.push([
				// 			this.categoryPriceList.find((f) => f.value === d.category).text
				// 		])
				// 		temp.push([d.number])
				// 		temp.push([
				// 			d.number *
				// 				parseFloat(
				// 					this.categoryPriceList.find((f) => f.value === d.category)
				// 						.text
				// 				)
				// 		])
				// 		temp.push([this.getFeatureName(d.feature)])
				// 		temp.push([this.getImg(d.category)])
				// 		csvRows.push(temp)
				// 	})
				// 	allTotal += total
				// 	csvRows.push(['合计总价', '', '', total])
				// 	csvRows.push([])
				// })
				// csvRows.push([
				// 	'全屋总价',
				// 	'',
				// 	'',
				// 	allTotal,
				// 	'优惠金额',
				// 	this.formData.discount
				// ])

				// const csvContent = csvRows
				// 	.map((row) => row.map((cell) => `"${cell}"`).join(','))
				// 	.join('\n')
				// const fileName = (this.formData.planName || '方案') + '.csv'

				// plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, (fs) => {
				// 	fs.root.getFile(fileName, { create: true }, (entry) => {
				// 		entry.createWriter((writer) => {
				// 			writer.onwrite = (e) => {
				// 				uni.showToast({ title: '导出成功', icon: 'success' })
				// 				plus.nativeUI.confirm(
				// 					'下载成功, 是否打开文件',
				// 					function (e) {
				// 						var index = e.index
				// 						if (index == 0) {
				// 							plus.runtime.openFile(entry.fullPath)
				// 						}
				// 					},
				// 					{
				// 						title: '文件',
				// 						buttons: ['是', '否'],
				// 						verticalAlign: 'center'
				// 					}
				// 				)
				// 			}
				// 			writer.onerror = (e) => {
				// 				uni.showToast({ title: '导出失败', icon: 'none' })
				// 			}
				// 			writer.write(csvContent)
				// 		})
				// 	})
				// })
				break
		}
	}
}
</script>
<style lang="scss" scoped>
.wrapper {
	display: flex;
	flex-direction: column;
}
.form-container {
	width: 90vw;
	background-color: white;
	border-radius: 20rpx;
	padding: 30rpx;
}
.space-wrapper {
	margin-top: 20rpx;
}

.button {
	margin-top: 20rpx;
}
.danger {
	color: white;
	margin-top: 20rpx;
	background-color: #f56c6c;
	border-color: #f56c6c;
}
::v-deep .uni-card {
	overflow: unset !important;
}

.uni-list-cell {
	background-color: #fff;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 20rpx;
	.uni-list-cell-left {
		font-size: 35rpx;
	}
}
.uni-list-cell-db {
	flex: 1;
}
.as-input {
	width: 100%;
	border: solid 1px #e5e5e5;
	border-radius: 10rpx;
	padding: 20rpx 10rpx;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	.customer-icon {
		padding: 0 0 0 5rpx;
	}
	.placeholder {
		font-size: 33rpx;
		color: #999;
	}
	.as-content {
		color: #333;
		font-size: 33rpx;
		width: 370rpx;
		text-align: right;
	}
}

.image-category {
	width: 200rpx;
	height: 200rpx;
}
.content-wrap {
	padding: 20rpx;
	padding-bottom: 120rpx;
}
.bottom {
	height: 120rpx;
	width: 750rpx;
	position: fixed;
	bottom: 0;
	background-color: white;
	display: flex;
	flex-direction: row;
	padding: 0 30rpx;
	// justify-content: center;
	align-items: center;
	font-size: 35rpx;
	color: #333;
	text {
		color: #f56c6c;
		font-size: 40rpx;
		margin-left: 20rpx;
	}
}
.fill {
	flex: 2;
}
.flex {
	flex: 1;
	display: flex;
	align-items: center;
}
.amount-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  background-color: #f5f5f5;
  border-radius: 12px;
  padding: 12px 0;
  margin: 10px;
}

.amount-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.value {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.profit-value {
  color: #07c160; /* 利润通常用绿色表示 */
}

.divider {
  width: 1px;
  height: 20px;
  background-color: #e0e0e0;
}
</style>
